package com.teamclub.app.sservices.systemmanager

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.app.sforms.AppOrgArchForm
import com.teamclub.domain.system.AppOrgArch
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.{F, TreeGenerator}
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import java.util.List

import com.teamclub.util.page.Pager
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

/**
  * Created by ilkkzm on 17-9-15.
  */
@Service
class AppOrgArchService {
  val treeGenerator = new TreeGenerator()

  def expr(where: ExpressionList[AppOrgArch], form: AppOrgArchForm) {
    if(form.getId != null) {
      where.eq("id", form.getId)
    }
    if(StringUtils.isNoneBlank(form.getOrganNo)) {
      where.eq("organNo", form.getOrganNo)
    }
    if(form.getLevel != null) {
      where.eq("level", form.getLevel)
    }
  }

  def list(form: AppOrgArchForm): F.Either[List[AppOrgArch], ErrorCode] = {
    val where = Ebean.find(classOf[AppOrgArch]).where().eq("level",1)
    expr(where, form)
    val list = where.findList()
    F.Either.Left(list)
  }

  def openWinList(form: AppOrgArchForm): F.Either[Pager[AppOrgArch], ErrorCode] = {
    val where = Ebean.find(classOf[AppOrgArch]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: AppOrgArchForm): F.Either[AppOrgArch, ErrorCode] = {
    var instance = new AppOrgArch
    if(form.id != null) {
      instance = Ebean.find(classOf[AppOrgArch], form.id)
    }
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.id != null) {
      instance.update()
    } else {
      if(form.parentId == null || form.parentId == 0) {
        var count: Integer = Ebean.find(classOf[AppOrgArch]).where().eq("organNo", form.getOrganNo).eq("level", 1).findCount()
        var code = "%03d".format(count + 1)
        instance.setLevel(1)
        instance.setArchCode(code)
      } else {
        val parentOrgArch = Ebean.find(classOf[AppOrgArch], form.parentId)
        val count = Ebean.find(classOf[AppOrgArch]).where()
          .eq("organNo", form.getOrganNo)
          .eq("level", parentOrgArch.getLevel + 1)
          .findCount()
        val code = parentOrgArch.getArchCode + "%03d".format(count + 1)
        instance.setLevel(parentOrgArch.getLevel + 1)
        instance.setArchCode(code)
      }
      instance.save()
    }
    F.Either.Left(instance)
  }

  def del(form: AppOrgArchForm): F.Either[AppOrgArch, ErrorCode] = {
    var instance = Ebean.find(classOf[AppOrgArch], form.id)
    if(instance == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    val result = instance.delete()
    if(result) F.Either.Left(instance) else F.Either.Right(ErrorCode.BIZ_FAILURE)
  }
}
